using System;
using System.Configuration;
using System.Web;

namespace ADEVSO.Web
{
    /// <summary>
    /// ADEVSO Global.asax
    /// </summary>
    public class GlobalApplication : HttpApplication
    {

        public String ConnectionStringName { get; set; }

        protected virtual void Application_Start(object sender, EventArgs e)
        {

        }

        protected virtual void Session_Start(object sender, EventArgs e)
        {
            //Set Session Database Connection
            Session["Connection"] = CreateConnection();
            // Other Session Variables
            Session["CurrentPage"] = null;
            Session["URLHistory"] = new UI.URLHistory();
            Session["CurrentCulture"] = ConfigurationManager.AppSettings["culture"];
        }

        protected virtual void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected virtual void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected virtual void Application_Error(object sender, EventArgs e)
        {

        }

        protected virtual void Session_End(object sender, EventArgs e)
        {
            ADEVSO.Data.Connection connection = (ADEVSO.Data.Connection)Session["Connection"];
            if (connection != null) connection.Dispose();
        }

        protected virtual void Application_End(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Set Database Connection
        /// </summary>
        /// <returns></returns>
        private Data.Connection CreateConnection()
        {

            Data.Connection connection = null;
            try
            {
                ConnectionStringSettings connectionString = String.IsNullOrEmpty(ConnectionStringName) ? ConfigurationManager.ConnectionStrings[0] : ConfigurationManager.ConnectionStrings[ConnectionStringName];
                connection = new Data.SqlClient.SqlServer(connectionString.ConnectionString);
            }
            catch
            {
            }
            return connection;
        }
    }
}